package com.amt.util;

import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;


/**
 * @author 江伟
 * @Title: HttpUtil.java
 * @Package com.amt.util
 * @Description: TODO(http工具类)
 * @date 2018年11月21日 下午2:59:56
 * Copyright (c) ©1994-2018 Scjydz.com All Rights Reserved.
 */
@SuppressWarnings("deprecation")
@Slf4j
@Component
public class HttpUtil {


    /**
     * @param source
     * @param encode
     * @description: url指定转码
     */
    public static String urlEncode(String source, String encode) {
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source, encode);
        } catch (UnsupportedEncodingException e) {
            log.error("url指定转码异常：{}", e);
            return "0";
        }
        return result;
    }

    /**
     * @param source
     * @description: url转成GBK编码
     */
    public static String urlEncodeGBK(String source) {
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source, "GBK");
        } catch (UnsupportedEncodingException e) {
            log.error("url转成GBK编码异常：{}", e);
            return "0";
        }
        return result;
    }

    /**
     * @param req_url http请求
     * @description: 发起get请求获取返回结果  (URLConnection处理)
     */
    public static String httpRequest(String req_url) {
        StringBuffer buffer = new StringBuffer();
        HttpURLConnection httpUrlConn = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            URL url = new URL(req_url);
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(false);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.setConnectTimeout(30000);
            httpUrlConn.setReadTimeout(30000);
            httpUrlConn.connect();

            // 将返回的输入流转换成字符串  
            inputStream = httpUrlConn.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

        } catch (Exception e) {
            log.error("发送GET请求出现异常！{}", e);
            return null;
        } finally {

            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                httpUrlConn.disconnect();
            } catch (IOException ex) {

            }
        }
        return buffer.toString();
    }

    /**
     * @param requestUrl
     * @description: 发送get请求取得返回的输入流
     */
    public static InputStream httpRequestIO(String requestUrl) {
        InputStream inputStream = null;
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoInput(true);
            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.setConnectTimeout(30000);
            httpUrlConn.setReadTimeout(30000);
            httpUrlConn.connect();
            // 获得返回的输入流  
            inputStream = httpUrlConn.getInputStream();
        } catch (Exception e) {
            log.error("GET输入流 出现异常！{}", e);
        }
        return inputStream;
    }


    /**
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     * @description:向指定URL发送GET方法的请求 (URLConnection处理)
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                log.info(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.error("发送GET请求出现异常！{}", e);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                log.error("关闭流异常：{}", e2);
            }
        }
        return result;
    }

    /**
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     * @description: 发起Post请求 (URLConnection处理)
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.error("发送 POST 请求出现异常！{}", e);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("关闭流异常：{}", ex);
            }
        }
        return result;
    }


    /**
     * @param url 发送请求的URL
     * @description: 无参数的 get请求 (HttpClient处理)
     */
    public static String requestGet(String url) {
        String respstring = null;
        HttpClient client = new HttpClient();
        // 设置连接超时时间
        client.getHttpConnectionManager().getParams().setConnectionTimeout(120000);
        GetMethod get = new GetMethod(url);
        try {
            if (get != null) {
                int statusCode = client.executeMethod(get);
                if (statusCode == HttpStatus.SC_OK) {
                    respstring = get.getResponseBodyAsString();
                }
            }

        } catch (HttpException e) {
            log.error("HTTP异常：{}", e);
        } catch (IOException e) {
            log.error("IO异常：{}", e);
        }
        return respstring;
    }

    /**
     * @param url 发送请求的URL
     * @description: 无参数的post请求(HttpClient处理)
     */
    public static String requestPost(String url) {
        HttpClient client = new HttpClient();
        // 设置连接超时时间
        client.getHttpConnectionManager().getParams().setConnectionTimeout(120000);
        PostMethod post = new PostMethod(url);
        InputStream ins = null;
        BufferedReader br = null;
        try {
            if (post != null) {
                client.executeMethod(post);
                ins = post.getResponseBodyAsStream();
                // 按指定的字符集构建文件流
                br = new BufferedReader(new InputStreamReader(ins, "utf-8"));
                StringBuffer sbf = new StringBuffer();
                String line = null;
                while ((line = br.readLine()) != null) {
                    sbf.append(line);
                }
                return sbf.toString();
            }
        } catch (HttpException e) {
            log.error("HTTP异常：{}", e);
        } catch (IOException e) {
            log.error("IO异常：{}", e);
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {

            }
            post.releaseConnection();
        }
        return null;
    }

    /**
     * @param url  发送请求的URL
     * @param parm json格式数据
     * @description: 带参数的post请求(HttpClient处理)
     */
    public static String requestPost(String url, String parm) {
        HttpClient client = new HttpClient();
        // 设置连接超时时间
        client.getHttpConnectionManager().getParams().setConnectionTimeout(120000);
        PostMethod post = new PostMethod(url);
        InputStream ins = null;
        BufferedReader br = null;
        StringBuffer sbf = new StringBuffer();
        try {
            RequestEntity entity = new StringRequestEntity(parm, "text/html", "utf-8");
            post.setRequestEntity(entity);
            client.executeMethod(post);

            ins = post.getResponseBodyAsStream();
            // 按指定的字符集构建文件流
            br = new BufferedReader(new InputStreamReader(ins, "utf-8"));

            String line = null;
            while ((line = br.readLine()) != null) {
                sbf.append(line);
            }


        } catch (HttpException e) {
            log.error("HTTP异常：{}", e);
            return null;
        } catch (IOException e) {
            log.error("IO异常：{}", e);
            return null;
        } finally {

            try {
                if (br != null) {
                    br.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {

            }
            post.releaseConnection();
        }

        return sbf.toString();

    }

    public static String requestPost2(String url, String parm) {
        HttpClient client = new HttpClient();
        // 设置连接超时时间
        client.getHttpConnectionManager().getParams().setConnectionTimeout(120000);
        PostMethod post = new PostMethod(url);
        InputStream ins = null;
        BufferedReader br = null;
        StringBuffer sbf = new StringBuffer();
        try {
            RequestEntity entity = new StringRequestEntity(parm, "application/json", "utf-8");
            post.setRequestEntity(entity);
            client.executeMethod(post);

            ins = post.getResponseBodyAsStream();
            // 按指定的字符集构建文件流
            br = new BufferedReader(new InputStreamReader(ins, "utf-8"));

            String line = null;
            while ((line = br.readLine()) != null) {
                sbf.append(line);
            }


        } catch (HttpException e) {
            log.error("HTTP异常：{}", e);
            return null;
        } catch (IOException e) {
            log.error("IO异常：{}", e);
            return null;
        } finally {

            try {
                if (br != null) {
                    br.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {

            }
            post.releaseConnection();
        }

        return sbf.toString();

    }

    /**
     * @param url 发送请求的URL
     * @param map 表单map
     * @description: 表单格式的 post请求(HttpClient处理)
     */
    public static String requestPost(String url, Map<String, String> map) {
        HttpClient client = new HttpClient();
        // 设置连接超时时间
        client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
        PostMethod post = new PostMethod(url);
        InputStream ins = null;
        BufferedReader br = null;
        try {
            //设置编码
            client.getParams().setContentCharset("UTF-8");
            //设置请求消息头，为表单方式提交
            post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            //设置参数
            Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> entry = iterator.next();
                post.setParameter(entry.getKey(), entry.getValue());
            }
            client.executeMethod(post);
            ins = post.getResponseBodyAsStream();
            // 按指定的字符集构建文件流
            br = new BufferedReader(new InputStreamReader(ins, "utf-8"));
            StringBuffer sbf = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                sbf.append(line);
            }

            br.close();
            return sbf.toString();
        } catch (HttpException e) {
            log.error("HTTP异常：{}{}", e);
        } catch (IOException e) {
            log.error("IO异常：{}{}", e);
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {

            }
            post.releaseConnection();
        }
        return null;

    }


    /**
     * @param wsdl   wsdl地址
     * @param xml    请求的xml
     * @param method 调用的方法名
     * @description: HttpURLConnection调用wsdl
     */
    public static String requestWSDL(String wsdl, String xml, String method) {
        OutputStreamWriter oStream = null;
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        HttpURLConnection con = null;
        try {
            URL url = new URL(wsdl);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Accept-Encoding", "gzip,deflate");
            con.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
            con.setRequestProperty("SOAPAction", method);
//	        con.setRequestProperty("action",method);
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setReadTimeout(30000);
            con.setConnectTimeout(30000);
            oStream = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            oStream.write(xml);
            oStream.flush();
            oStream.close();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                sbf.append(line);
            }
            reader.close();
            oStream.close();

        } catch (Exception e) {
            log.error("wsdl请求出现异常！{}", e);
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (oStream != null) {
                    oStream.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                log.error("流关闭异常：{}", ex);
            }
            con.disconnect();
        }
        return sbf.toString();
    }


    /**
     * @param address 地址
     * @param xml     xml参数
     * @return
     * @description: webservice请求
     */
    public static String requestWebservice(String address, String xml) {
        HttpURLConnection con = null;
        OutputStreamWriter oStream = null;
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            URL url = new URL(address);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Accept-Encoding", "gzip,deflate");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setReadTimeout(30000);
            con.setConnectTimeout(30000);
            oStream = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            oStream.write(xml);
            oStream.flush();
            oStream.close();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                sbf.append(line);
            }

        } catch (Exception e) {
            log.error("流异常：{}", e);
            return null;
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (oStream != null) {
                    oStream.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                log.error("流异常：{}", ex);
            }
            con.disconnect();
        }
        return sbf.toString();
    }

    /**
     * @param url 发送请求的URL
     * @param map json格式数据
     * @description: 带参数的post请求(HttpClient处理)
     */
    public static String YWXOPENIDPost(String url, Map<String, Object> map) {
        HttpClient client = new HttpClient();
        // 设置连接超时时间
        client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
        PostMethod post = new PostMethod(url);
        InputStream ins = null;
        BufferedReader br = null;
        try {
            RequestEntity entity = new StringRequestEntity(JSONArray.toJSONString(map), "application/json", "utf-8");
            post.setRequestEntity(entity);
            client.executeMethod(post);

            ins = post.getResponseBodyAsStream();
            // 按指定的字符集构建文件流
            br = new BufferedReader(new InputStreamReader(ins, "utf-8"));
            StringBuffer sbf = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                sbf.append(line);
            }

            return sbf.toString();
        } catch (HttpException e) {
            log.error("HTTP异常：{}", e);
        } catch (IOException e) {
            log.error("IO异常：{}", e);
        } finally {

            try {
                if (br != null) {
                    br.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {

            }
            post.releaseConnection();
        }
        return null;

    }



    /**
     * @param urls 接口方法
     * @param xml
     * @return 接口调用josn字符串
     * @description: HttpURLConnection远程执行POST方法调用外部接口
     */
    public static String requestPostTwo(String urls, String xml) {
        HttpURLConnection con = null;
        OutputStreamWriter oStream = null;
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            URL url = new URL(urls);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Accept-Encoding", "gzip,deflate");
            con.setRequestProperty("Content-Type", "application/json");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setReadTimeout(30000);
            con.setConnectTimeout(30000);
            oStream = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            oStream.write(xml);
            oStream.flush();
            oStream.close();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                sbf.append(line);
            }
        } catch (Exception e) {
            log.error("HTTP异常：{}", e);
            return null;
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (oStream != null) {
                    oStream.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {

            }
            con.disconnect();
        }
        return sbf.toString();
    }

    /**
     * @param url 发送请求的URL
     * @param map json格式数据
     * @description: 带参数的post请求(HttpClient处理)
     */
    public static String YWXUserStatusPost(String url, Map<String, Object> map) {
        HttpClient client = new HttpClient();
        // 设置连接超时时间
        client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
        PostMethod post = new PostMethod(url);
        InputStream ins = null;
        BufferedReader br = null;
        StringBuffer sbf = new StringBuffer();
        try {
            RequestEntity entity = new StringRequestEntity(JSONArray.toJSONString(map), "application/json", "utf-8");
            post.setRequestEntity(entity);
            client.executeMethod(post);
            ins = post.getResponseBodyAsStream();
            // 按指定的字符集构建文件流
            br = new BufferedReader(new InputStreamReader(ins, "utf-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                sbf.append(line);
            }
        } catch (HttpException e) {
            log.error("HTTP异常：{}", e);
            return null;
        } catch (IOException e) {
            log.error("IO异常：{}", e);
            return null;
        } finally {

            try {
                if (br != null) {
                    br.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {

            }
            post.releaseConnection();
        }
        return sbf.toString();

    }

    /**
     * @param method 接口方法
     * @param xml    传参格式为<id>1</id><name>张三</name>
     * @return 接口调用XML字符串
     * @description: HttpURLConnection远程执行POST方法调用外部接口
     */
    public static String requestWSDL2(String address, String method, String xml) {
        OutputStreamWriter oStream = null;
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            URL url = new URL(address + method);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Accept-Encoding", "gzip,deflate");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setConnectTimeout(20000);
            con.setReadTimeout(20000);
            oStream = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            oStream.write(xml);
            oStream.flush();
            oStream.close();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                sbf.append(line);
            }
            reader.close();
            oStream.close();
            con.disconnect();
        } catch (Exception e) {

        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (oStream != null) {
                    oStream.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {

            }
        }
        return sbf.toString();
    }

    /**
     * 从网络Url中下载文件
     *
     * @param downloadUrl 下载地址
     * @param fileName    文件名称
     * @param savePath    保存路径
     */
    public static String downLoadFromUrl(String downloadUrl, String fileName, String savePath) {
        try {
            URL url = new URL(downloadUrl);
            HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
            httpUrlConnection.setReadTimeout(30000);
            httpUrlConnection.setConnectTimeout(30000);
            httpUrlConnection.setDoInput(true);
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setUseCaches(false);
            httpUrlConnection.setRequestMethod("GET");
            httpUrlConnection.setRequestProperty("Charsert", "UTF-8");
            InputStream inputStream = httpUrlConnection.getInputStream();
            byte[] buffer = readInputStream(inputStream);

            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            String pathName = saveDir + File.separator + fileName;
            File file = new File(pathName);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(buffer);
            fos.close();
            inputStream.close();
            return pathName;
        } catch (IOException e) {
            log.error("下载对账文件http异常,{}", e.getMessage());
        }
        return null;
    }

    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
}